package io.osw.modules.sys.service.impl;

import io.osw.common.annotation.DataFilter;
import io.osw.common.utils.Constant;
import io.osw.modules.sys.entity.*;
import io.osw.modules.sys.service.SysDeptService;
import io.osw.modules.sys.service.SysUserService;
import io.osw.modules.sys.service.TblCompanyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.osw.common.utils.PageUtils;
import io.osw.common.utils.Query;

import io.osw.modules.sys.dao.TblSchoolDao;
import io.osw.modules.sys.service.TblSchoolService;


@Service("tblSchoolService")
public class TblSchoolServiceImpl extends ServiceImpl<TblSchoolDao, TblSchoolEntity> implements TblSchoolService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TblCompanyService tblCompanyService;

    @Autowired
    private SysDeptService sysDeptService;

    @Override
    @DataFilter(subDept = true, user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String schoolName = (String) params.get("schoolName");
        Page<TblSchoolEntity> page = this.selectPage(
                new Query<TblSchoolEntity>(params).getPage(),
                new EntityWrapper<TblSchoolEntity>()
                        .like(StringUtils.isNotBlank(schoolName), "school_name", schoolName)
                        .addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))

        );
        List<TblSchoolEntity> records = page.getRecords();

        for (TblSchoolEntity record : records) {
            if (record == null) {
                return null;
            }

            //注入校长名
            SysUserEntity sysUserEntity = sysUserService.selectById(record.getPrincipalId());
            record.setPrincipalName(sysUserEntity.getUsername());

            //注入教师组长名
            SysUserEntity sysUserEntity1 = sysUserService.selectById(record.getTrsId());
            record.setUsername(sysUserEntity1.getUsername());

            //注入公司名
            TblCompanyEntity tblCompanyEntity = tblCompanyService.selectById(record.getCompanyId());
            record.setCompanyName(tblCompanyEntity.getCompanyName());

            //注入区域
            SysDeptEntity sysDeptEntity = sysDeptService.selectById(record.getDeptId());
            String deptLevel = sysDeptEntity.getDeptLevel();
            if (StringUtils.isNotBlank(deptLevel)){
                record.setArea(sysDeptEntity.getName());
            }else{
                record.setArea("");
            }

        }

        return new PageUtils(page);
    }


}
